package com.lin.controller;


import cn.hutool.core.bean.BeanUtil;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.lin.constant.UserConstants;
import com.lin.entity.R;
import com.lin.entity.dto.UserDTO;
import com.lin.entity.query.UserQuery;
import com.lin.entity.vo.PageVO;
import com.lin.entity.vo.UserVO;
import com.lin.exception.UserIdNullException;
import com.lin.service.IUserService;
import com.lin.utils.JWTUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {
    @Resource
    private IUserService userService;

    /**
     * 注册 --需要将密码加密处理
     * @param userDTO 用户信息
     * @return R
     */
    @PostMapping("/register")
    public R register(@RequestBody UserDTO userDTO) {
        return userService.register(userDTO);
    }

    /**
     * 登录
     * @param userDTO 用户信息
     * @return R -包含JWT令牌信息
     */
    @PostMapping("/login")
    public R login(@RequestBody UserDTO userDTO, HttpServletRequest request) {
        R res = userService.login(userDTO);
        String token = (String) res.getData();
        // 若token不为null或空字符串, 设置JWT令牌到响应头中
        if (token != null && !token.isEmpty()) {
            request.getSession().setAttribute(UserConstants.JWT_HEADER_INFO, token);
        }
        return res;
    }

    /**
     * 获取当前用户信息
     * @param request 请求
     * @return R
     */
    @GetMapping
    public R getCurrentUserInfo(HttpServletRequest request) {
        String token = (String) request.getSession().getAttribute(UserConstants.JWT_HEADER_INFO);

        String token_prefix = UserConstants.TOKEN_PREFIX;

        // 去除token前缀
        if (token != null && token.startsWith(token_prefix)) {
            token = token.substring(token_prefix.length());
            DecodedJWT decodedJWT = JWTUtil.decodeAndVerify(token);

            // 获取当前用户名
            String username = decodedJWT.getClaim("username").asString();

            // 根据用户名查询用户信息 --用户名唯一
            UserVO currentUserInfo = null;

            // 获取当前用户信息
            try {
                currentUserInfo = userService.getCurrentUserInfo(username);
            } catch (JsonProcessingException e) {
                return R.error("获取当前用户信息失败", null);
            }

            // 判断当前用户信息是否为空
            if (currentUserInfo == null)
                return R.failed("获取当前用户信息失败", null);
            return R.ok("获取当前用户信息成功", currentUserInfo);
        }
        return R.failed("token为空, 用户未登录, 拒绝请求", null);
    }

    /**
     * 分页查询用户信息
     * @param userQuery 查询条件
     * @return R
     */
    @GetMapping("/page")
    public R listUsers(@RequestBody UserQuery userQuery) {
        if (userQuery == null)
            return R.failed("查询条件为空", null);

        PageVO<UserVO> userVOPageVO = null;

        try {
            userVOPageVO = userService.listUsers(userQuery);
        } catch (JsonProcessingException e) {
            R.error("获取用户列表失败", null);
        }

        if (userVOPageVO != null) {
            return R.ok("获取用户列表成功",
                    BeanUtil.copyProperties(userVOPageVO, PageVO.class));
        }
        return R.failed("获取用户列表失败", null);
    }


    /**
     * 删除用户--逻辑删除
     * @param id 用户ID
     * @return R
     */
    @PostMapping("/{id}")
    public R deleteUser(@PathVariable Integer id) {
        if (id == null)
            throw new UserIdNullException("用户ID为空");

        boolean status = userService.logicRemoveById(id);

        if (status)
            return R.ok("删除用户成功", null);
        return R.failed("删除用户失败", null);
    }

}
